$(function() {
	$('.datepicker').datepicker({dateFormat:"yy-mm-dd"});
	if($(window).width() < 1100) {
		$('#content').css('margin-right', 0);
		$('#content').css('margin-left', 0);
	}
});

function initCalendar() {
	$('#calendar').fullCalendar({
		events: '/calendar',
    eventTextColor: '#ffffff'
	});
}

function initTasks() {
	$('#save').click(function() {
		$('#criteria_save').dialog({
			height: 200,
			modal: true
		});
		
		$('#criteria_fields_save').html($('#criteria_fields').html());
		
		searchForm = $('#search_form');
		saveForm = $('#save_form');
		
	    $(':input[name]', searchForm).each(function() {
	        $('[name=' + $(this).attr('name') +']', saveForm).val($(this).val())
	    });
	    
		$('#criteria_save').show();
	});
	
	$('#id_criteria_select').change(function() {
		var id = $('#id_criteria_select').val();
		if(id != null && id.length > 0) {
			window.location = '/criteria/' + id + '/';
		}
	});
}

function initTask() {
	function onParentChange() {
		var value = $('#id_parent').val();
		if (value != null && value != '') {
			$('#parent_goto').html("<a id='parent_goto' href='/task/view/" + value + "/'>View</a>");
		}
		else {
			$('#parent_goto').html("<a id='parent_goto' style='display:none;' href='/'>View</a>");
		}
	}
	$('#id_parent').parent().append("<a id='parent_goto' href='/'>View</a>");
	$('#id_parent').change(onParentChange);
	onParentChange();
	
	//Write the revisions selected on our hidden select element onto the page
	function writeRevisions() {
		var rev_ids = $('#id_revisions').val();
		var list = "";
		if (rev_ids != null && rev_ids.length > 0) {
			list += "<hr/>";
		} else {
			$('#revision_list').html('');
			return;
		}
		for(var i = 0; i < rev_ids.length; i++) {
			list += $('#rev_' + rev_ids[i]).html() + "<hr/>";
		}
		$('#revision_list').html(list);
		
		//Create remove buttons
		$('#revision_list button').each(function () {
			var id = parseInt(this.id.substring('add_rev_'.length), 10);
			$(this).attr('id', 'remove_rev_' + id);
			$(this).text('Remove');
			$(this).click(function () {
				var revs = $('#id_revisions').val();
				for (var i = 0; i < revs.length; i++) {
					if(revs[i] == id) {
						revs.splice(i, 1);
						$('#id_revisions').val(revs);
						break;
					}
				}
				writeRevisions();
			});
		});
	}
	
	$('#add_revisions').click(function() {
		$('#select_revision').dialog({
			width: $(window).width() * .5,
			height: $(window).height() * .5,
			modal: true
		});
	});
	
	$('.revision button').click(function () {
		var rev_id = parseInt(this.id.substring('add_rev_'.length), 10);
		var revs = $('#id_revisions').val();
		if(revs ==  null) {
			revs = [];
		}
		revs.push(rev_id);
		$('#id_revisions').val(revs);
		$('#select_revision').dialog('close');
		writeRevisions();
	});
	
	writeRevisions();
}
